//
//  字符串匹配.swift
//  Swift-LeetCode
//
//  Created by 卢悦明 on 2024/3/6.
//

import UIKit

class StringPattern: NSObject {
    
    func QA() {
        print(indexOf3("Hello World", "H") == 0)
        print(indexOf3("Hello World", "or") == 7)
        print(indexOf3("Hello World", "abc") == -1)

    }
    
    /// 蛮力
    /// - Parameters:
    ///   - text: 原始字符串
    ///   - pattern: 匹配的字符串
    /// - Returns: 结果
    func indexOf1(_ text: String, _ pattern: String) -> Int {
        if text.count == 0 || pattern.count == 0 || text.count < pattern.count {
            return -1
        }
        let tArray = Array(text)
        let pArray = Array(pattern)
        let tlen = tArray.count
        let plen = pArray.count
        var pi = 0
        var ti = 0
        while ti < tlen && pi < plen {
            if tArray[ti] == pArray[pi] {
                pi += 1
                ti += 1
            } else {
                ti = ti - pi + 1
                pi = 0
            }
        }
        if pi == plen {
            return ti - pi
        } else {
            return -1
        }
    }
    /// 蛮力—优化1
    /// - Parameters:
    ///   - text: 原始字符串
    ///   - pattern: 匹配的字符串
    /// - Returns: 结果
    func indexOf2(_ text: String, _ pattern: String) -> Int {
        if text.count == 0 || pattern.count == 0 || text.count < pattern.count {
            return -1
        }
        let tArray = Array(text)
        let pArray = Array(pattern)
        let tlen = tArray.count
        let plen = pArray.count
        var pi = 0
        var ti = 0
        while pi < plen && ti-pi <=  tlen - plen {
            if tArray[ti] == pArray[pi] {
                pi += 1
                ti += 1
            } else {
                ti = ti - pi + 1
                pi = 0
            }
        }
        if pi == plen {
            return ti - pi
        } else {
            return -1
        }
    }
    /// 蛮力—优化2
    /// - Parameters:
    ///   - text: 原始字符串
    ///   - pattern: 匹配的字符串
    /// - Returns: 结果
    func indexOf3(_ text: String, _ pattern: String) -> Int {
        if text.count == 0 || pattern.count == 0 || text.count < pattern.count {
            return -1
        }
        let tArray = Array(text)
        
        let pArray = Array(pattern)
        let tlen = tArray.count
        let plen = pArray.count
        
        var pi = 0
        var ti = 0
        while pi < plen && ti <=  tlen - plen {
            if tArray[ti + pi] == pArray[pi] {
                pi += 1
            } else {
                ti += 1
                pi = 0
            }
        }
        if pi == plen {
            return ti
        } else {
            return -1
        }
    }
}
